package com.sharemarking.application.common.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.sharemarking.application.common.BaseSpecification;
import com.sharemarking.application.common.entity.OwnQusetion;
import com.sharemarking.application.common.repository.OwnQusetionRepo;


@Controller
@RequestMapping("ownQusetion")
public class OwnQusetionController {
	
	@Autowired
	private OwnQusetionRepo qqr;
	

	/**
	 * 问题反馈数据列表
	 * 
	 * @param e
	 * @param page
	 * @param size
	 * @param model
	 */
	@GetMapping(value ="index")
	@PreAuthorize("hasPermission('sys:ownquestion',1)")
	public void index(OwnQusetion e, Integer page, Integer size, Model model) {
		if (page == null) {
			page = 0;
		} else {
			page -= 1;
		}
		if (size == null) {
			size = 10;
		}
		// 按id降序排列
		Sort sort = new Sort(Direction.DESC, "id");
		PageRequest req = new PageRequest(page, size, sort);
		Page<OwnQusetion> p = qqr.findAll(new BaseSpecification<OwnQusetion>(e),req);
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/question/";
		model.addAttribute("pro", pro);
		model.addAttribute("page", p);
		model.addAttribute("search", e);

	}
	

	/**
	 * 获取实体添加,编辑接口
	 * 
	 * @param obj
	 * @param model
	 * @return
	 */
	@GetMapping(value = "{id}")
	@PreAuthorize("hasPermission('sys:ownquestion',1)")
	public String get(OwnQusetion obj, Model model) {
		if (obj.getId() != 0)
			obj = qqr.findOne(obj.getId());
		String pro="http://113.71.26.27:8080/tpl/public/uploadImage/question/";
		model.addAttribute("pro", pro);
		model.addAttribute("obj", obj);

		return "ownQusetion/form";
	}
	

	/**
	 * 问题添加和编辑
	 * 
	 * @param target
	 * @param PICN
	 * @return
	 * @throws IOException
	 */
	@PostMapping(value = "{id}")
	@Transactional
	@PreAuthorize("hasPermission('sys:ownquestion',#target.id==0?8:4)")
	public String index(OwnQusetion target,@RequestParam("PICN") MultipartFile PICN, HttpServletRequest request) throws IOException {
				// 文件上传
//				String PICName = null;

				if (!PICN.isEmpty()) {
					
					MultipartFile file = PICN;
//					PICName = file.getOriginalFilename();
					// 把要上传的图片转换成流
					InputStream isRef = file.getInputStream();
		 
					// 获取classes下的路径
//					String path = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/question/";
					String targetDir1 = this.getClass().getClassLoader().getResource("").getPath() + "public/uploadImage/question";
					File file1 = new File(targetDir1);
					file1.mkdirs();
					
					// 图片命名为loginName+Data+8位随机数.png
					Date now = new Date();
					SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");// 可以方便地修改日期格式

					String Date = dateFormat.format(now);
					StringBuilder str = new StringBuilder();// 定义变长字符串

					// 随机生成数字，并添加到字符串
					Random random = new Random();
					for (int i = 0; i < 8; i++) {
						str.append(random.nextInt(10));
					}

//					String path2 = path + Date + str.toString() + ".png";
					String path3 = Date + str.toString() + ".png";
					
					File targetFile = new File(targetDir1, path3);
					// 通过输出流将图片写入到相应的地方
					FileOutputStream fosRef = new FileOutputStream(targetFile);
					IOUtils.copy(isRef, fosRef);
					
					// 添加
					if (target.getId() == 0) {

						// 将接收的文件保存到指定文件中
						target.setPhoto(path3);
						// 保存图片路径
						PICN.transferTo(targetFile);
						
						qqr.save(target);
						return "redirect:index";
					} else {
						// 编辑
						OwnQusetion ownQusetion = qqr.findOne(target.getId());
						if (ownQusetion == null)
							return null;
						
						// 将接收的文件保存到指定文件中
						PICN.transferTo(targetFile);
						ownQusetion.setState(target.getState());
						
					}
				}else{
					// 当PICN为空时 编辑
					OwnQusetion ownQusetion = qqr.findOne(target.getId());
					if (ownQusetion == null)
						return null;
					
					ownQusetion.setState(target.getState());
					return "redirect:index";
				}
		return "redirect:index";
	}

	/**
	 * 删除问题反馈信息
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping(value = "{id}/delete")
	@Transactional
//	@PreAuthorize("hasPermission('sys:ownquestion',16)")
	public String delete(@PathVariable("id") Integer id) {
		qqr.findOne(id).setDelFlag(true);
		return "redirect:../index";
	}
	
	
}
